<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>infinite-scroll</title>
    <link rel="stylesheet" href="css/scroll.css">
</head>

<body>
    <div class="container">
        <h1>编程语录</h1>
        <div class="quotes"></div>
        <div class="loader">
            <div></div>
            <div></div>
            <div></div>
        </div>
        <!-- <button id="loadMore">加载更多</button> -->
    </div>
    <script>
        (function () {
            const quotesEl = document.querySelector('.quotes');
            const loaderEl = document.querySelector('.loader');
            // get the quotes from API
            const getQuotes = async (page, limit) => {
                const API_URL = `https://api.javascripttutorial.net/v1/quotes/?page=${page}&limit=${limit}`;
                const response = await fetch(API_URL);
                // handle 404
                if (!response.ok) {
                    throw new Error(`An error occurred: ${response.status}`);
                }
                return await response.json();
            }
            // show quotes
            const showQuotes = (quotes) => {
                quotes.forEach(quote => {
                    const quoteEl = document.createElement('div');
                    quoteEl.classList.add('quote');
                    quoteEl.innerHTML = `
                       <span>${quote.id})</span>
                        ${quote.quote}
                        <footer>${quote.author}</footer>
                    `;
                    quotesEl.appendChild(quoteEl);
                });
            };
            const hideLoader = () => {
                loaderEl.classList.remove('show');
            };
            const showLoader = () => {
                loaderEl.classList.add('show');
            };
            const hasMoreQuotes = (page, limit, total) => {
                const startIndex = (page - 1) * limit + 1;
                return total === 0 || startIndex < total;
            };
            // load quotes
            const loadQuotes = async (page, limit) => {

                // show the loader
                showLoader();

                // 0.5 second later
                setTimeout(async () => {
                    try {
                        // if having more quotes to fetch
                        if (hasMoreQuotes(page, limit, total)) {
                            // call the API to get quotes
                            const response = await getQuotes(page, limit);
                            // show quotes
                            showQuotes(response.data);
                            // update the total
                            total = response.total;
                        }
                    } catch (error) {
                        console.log(error.message);
                    } finally {
                        hideLoader();
                    }
                }, 500);
            };

            // control variables
            let currentPage = 1;
            const limit = 10;
            let total = 0;

            window.addEventListener('scroll', () => {
                const {
                    scrollTop,
                    scrollHeight,
                    clientHeight
                } = document.documentElement;

                if (scrollTop + clientHeight >= scrollHeight - 5 &&
                    hasMoreQuotes(currentPage, limit, total)) {
                    currentPage++;
                    loadQuotes(currentPage, limit);
                }
            }, {
                // 当你在添加事件监听器时设置它，就表示告诉浏览器该事件处理函数不会调用 preventDefault() 来阻止事件的默认行为。
                // 这样浏览器可以在事件触发时立即执行默认行为
                passive: true
            });

            // initialize
            loadQuotes(currentPage, limit);
        })();
    </script>
</body>

</html>